package com.sgb.member.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;

import com.sgb.member.MemberConfig;
import com.sgb.member.R;
import com.sgb.member.databinding.ActivityPersonApplyJoinBinding;
import com.sgb.member.databinding.ActivityPersonInviteJoinBinding;
import com.sgb.member.di.DaggerMemberComponent;
import com.sgb.member.di.MemberModule;
import com.sgb.member.entity.MemberProfileBean;
import com.sgb.member.entity.ParamDtosEntity;
import com.sgb.member.entity.PeronMemberJoinEntity;
import com.sgb.member.entity.PersonJoinDetailBean;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.entity.UserMsgEntity;
import com.sgb.member.view_model.PersonInviteJoinModel;
import com.sgb.member.weight.AppendFieldsView;
import com.sgb.member.weight.NumberInputFilter;
import com.sgb.member.weight.SimpleResult;
import com.swgk.core.base.AppActivity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

public class PersonInviteJoinActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    @Inject
    PersonInviteJoinModel sModel;
    private ActivityPersonInviteJoinBinding mBinding;
    private List<CommonPopEntity> memberTypes;

    private QualityMemberBean memberBean;
    private boolean isFlag; // 是否重复提交
    private PeronMemberJoinEntity mJoinEntity;

    public static void start(Activity context, QualityMemberBean memberBean, boolean isFlag) {
        Intent intent = new Intent(context, PersonInviteJoinActivity.class);
        intent.putExtra("bean", memberBean);
        intent.putExtra("isFlag", isFlag);
        context.startActivityForResult(intent, MemberConfig.REQ_SERVICE);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMemberComponent.builder()
                .appComponent(appComponent)
                .memberModule(new MemberModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        super.initView();
        memberBean = (QualityMemberBean) getIntent().getSerializableExtra("bean");
        isFlag = getIntent().getBooleanExtra("isFlag", false);
        if (memberBean == null) {
            finish();
            return;
        }
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_person_invite_join);
        mBinding.setViewModel(memberBean);
        mBinding.activityBar.titleView.setText("邀请加盟");
        mBinding.activityBar.ivBack.setOnClickListener(v -> onBackPressed());
        mBinding.tvCompany.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MemberConfig.getInstance().startWebsiteInfo(getActivity(), memberBean.getCompanyNo(), 1);
            }
        });
        mBinding.submit.setOnClickListener(v -> {
            if (!ClickUtils.isDoubleClick()) {
                submitInfo();
            }
        });
        initEntityInfo();
        sModel.getCompanyProfile(memberBean.getCompanyNo());
    }

    /**
     * 初始化获取企业信息
     */
    private void initEntityInfo() {
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        String companyName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        String userName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
        String userNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        String userPhone = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "");
        mJoinEntity = new PeronMemberJoinEntity();
        mJoinEntity.setNo("");
        mJoinEntity.setApplyCompanyName(memberBean.getCompanyName()); // 申请企业名称
        mJoinEntity.setApplyCompanyNo(memberBean.getCompanyNo()); // 申请企业no
        mJoinEntity.setRelation("1");//供需关系 1.供方会员 2.需方会员
        mJoinEntity.setLevel("普通会员");
        mJoinEntity.setApplyType("2"); //申请类型 1企业申请.邀请 2 个人申请.邀请
        mJoinEntity.setJoinWay("2"); //途径方式 1:申请 2：邀请
        mJoinEntity.setInviteContent(""); //邀请内容
        // 个人用户信息
        mJoinEntity.setUserNo(userNo);
        mJoinEntity.setUserContactName(userName);
        mJoinEntity.setUserContactPhone(userPhone);
        mJoinEntity.setUserName(userName);
        mJoinEntity.setUserPhone(userPhone);

        mBinding.itemApplyUser.setContent(userName);
        mBinding.itemContacts.setContent(userName);
        mBinding.itemContactsPhone.setContent(userPhone);

        mBinding.tvAddress.setText(getText(memberBean.getAddress()));
        mBinding.itemCompany.setContent(memberBean.getCompanyName());
        mBinding.itemRelation.setContent("供方会员"); // 默认选中供方会员
        mBinding.itemLever.setContent("普通会员"); // 默认选中普通会员
        mBinding.itemLever.setOnWholeItemClickListener(this);
        mBinding.itemRelation.setOnWholeItemClickListener(this);
        mBinding.itemType.setOnWholeItemClickListener(this);

        mBinding.itemContacts.setInfilterType(ItemInputTextView.TYPE_TEXT);
        mBinding.itemContactsPhone.setInputType(InputType.TYPE_CLASS_PHONE);
        mBinding.itemContactsPhone.setMaxSize(11);
        mBinding.itemCooperationExpected.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        mBinding.itemMemberRequirements.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        mBinding.itemCooperationExpected.setFilters(new NumberInputFilter[]{new NumberInputFilter(99999999999.99, 0.01, 2)});
        mBinding.itemMemberRequirements.setFilters(new NumberInputFilter[]{new NumberInputFilter(99999999999.99, 0.01, 2)});
    }


    /**
     * 更新会员信息
     */
    public void setMemberProfile(MemberProfileBean data) {
        String concat = getText(data.getCurrentCompanyConstracts());
        String phone = getText(data.getCurrentCompanyPhone());
        mBinding.tvTopContacts.setText(String.format("%s | %s", concat, phone));
        mBinding.itemUser.setContent(getText(data.getCurrentCompanyBusinessOwner()));
        // 申请企业信息
        mJoinEntity.setApplyCompanyBusinessOwner(data.getCurrentCompanyBusinessOwner()); // 负责人
        mJoinEntity.setApplyCompanyContacts(data.getCurrentCompanyConstracts()); // 申请企业联系电话
        mJoinEntity.setApplyCompanyPhone(data.getCurrentCompanyPhone()); // 申请企业联系电话
        if (isFlag) {
            mJoinEntity.setNo(memberBean.getNo());
            sModel.getMemberDetail(memberBean.getNo());
        }
    }

    public void setInviteRecordDetail(PersonJoinDetailBean data) {
        mBinding.itemLever.setContent(StringUtil.getNotEmptyStr(data.companyLevel));
        //供需关系 1.供方会员 2.需方会员
        if (!TextUtils.isEmpty(data.relation)) {
            if (TextUtils.equals("1", data.relation)) {
                mBinding.itemRelation.setContent("供方会员");
            } else {
                mBinding.itemRelation.setContent("需方会员");
            }
        }
        mBinding.itemType.setContent(formatListToString(data.companyAllCategoryName));
        mBinding.cfkBusiness.setEditContent(StringUtil.getNotEmptyStr(data.applyBusiness));
        mBinding.cfkNotes.setEditContent(StringUtil.getNotEmptyStr(data.invitationInstructions));
        mBinding.itemContacts.setContent(StringUtil.getNotEmptyStr(data.userName));
        mBinding.itemContactsPhone.setContent(StringUtil.getNotEmptyStr(data.userPhone));
        mBinding.itemCooperationExpected.setContent(data.cooperationExpected); // 合作预期
        mBinding.itemMemberRequirements.setContent(data.membershipRequirements); // 会费要求
        // 邀请企业信息
        mJoinEntity.setLevel(data.companyLevel);
        mJoinEntity.setRelation(data.relation);
        mJoinEntity.setInviteContent(data.invitationInstructions); // 申请描述
        mJoinEntity.setInvitationInstructions(data.invitationInstructions); // 申请描述
        mJoinEntity.setApplyBusiness(data.applyBusiness); // 申请业务
        mJoinEntity.setUserName(data.userName);
        mJoinEntity.setUserPhone(data.userPhone); //用户联系名
        mJoinEntity.setCooperationExpected(data.cooperationExpected); // 合作预期
        mJoinEntity.setMembershipRequirements(data.membershipRequirements); // 会费要求
        mJoinEntity.setCooperationBusiness(data.applyReason); // 合作业务
        mJoinEntity.setFirstCategory(getArrays(data.companyFirstCategory));
        mJoinEntity.setSecondCategory(getArrays(data.companySecondCategory));
        mJoinEntity.setThirdCategory(getArrays(data.companyThirdCategory));
        mJoinEntity.setFourCategory(getArrays(data.companyFourCategory));
        mJoinEntity.setFiveCategory(getArrays(data.companyFiveCategory));
        List<ParamDtosEntity> paramDtos = new ArrayList<>();
        List<PersonJoinDetailBean.VdefListBean> appendFields = data.vdefList; //用户联系名
        if (appendFields != null && appendFields.size() > 0) {
            for (PersonJoinDetailBean.VdefListBean appendField : appendFields) {
                if (!TextUtils.isEmpty(appendField.title) && !TextUtils.isEmpty(appendField.content)) {
                    paramDtos.add(new ParamDtosEntity(appendField.title, appendField.content));
                }
            }
        }
        mJoinEntity.setParamDtos(paramDtos);
    }

    private String getText(String text) {
        if (StringUtil.isEmpty(text)) {
            return "暂无数据";
        }
        return text;
    }

    public static String formatListToString(List<String> str) {
        if (str == null || str.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (String s : str) {
            sb.append(s).append(",");
        }
        return sb.substring(0, sb.length() - 1);
    }

    /**
     * 个人加盟成功
     */
    public void memberJoinSuccess() {
        MToast.showToast(this, "提交成功");
        Intent intent = new Intent();
        intent.putExtra(MemberConfig.JUMP_RECORD, true);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void OnWholeItemClick(View view) {
        int id = view.getId();
        if (id == R.id.item_lever) {
            // 会员等级
            sModel.showMemberLeverPop(mBinding.itemLever, new SimpleResult<CommonPopEntity>() {
                @Override
                public void onResult(CommonPopEntity commonPopEntity, Object... objects) {
                    mJoinEntity.setLevel(commonPopEntity.getTypeName());
                }
            });
        } else if (id == R.id.item_relation) {
            sModel.showSupplyDemandPop(mBinding.itemRelation, new SimpleResult<CommonPopEntity>() {
                @Override
                public void onResult(CommonPopEntity commonPopEntity, Object... objects) {
                    // 设置供需关系
                    if (!TextUtils.equals(commonPopEntity.getNo(), mJoinEntity.getRelation())) {
                        memberTypes = new ArrayList<>();
                        mBinding.itemType.setContent("");
                    }
                    mJoinEntity.setRelation(commonPopEntity.getNo());
                }
            });
        } else if (id == R.id.item_type) {
            if (TextUtils.isEmpty(mBinding.itemRelation.getContent())) {
                MToast.showToast(this, "请选择供需关系");
                return;
            }
            if (TextUtils.equals("1", mJoinEntity.getRelation())) {
                // ascription 0 供方 1需方
                ChooseMemberTypeActivity.start(this, memberTypes, "0", MemberConfig.REQ_MEMBER_TYPE);
            } else {
                ChooseMemberTypeActivity.start(this, memberTypes, "1", MemberConfig.REQ_MEMBER_TYPE);
            }
        }
    }

    private void submitInfo() {
        if (TextUtils.isEmpty(mBinding.itemLever.getContent())) {
            MToast.showToast(this, "请选择会员等级");
            return;
        }
        if (TextUtils.isEmpty(mBinding.itemRelation.getContent())) {
            MToast.showToast(this, "请选择供需关系");
            return;
        }
        if (TextUtils.isEmpty(mBinding.itemType.getContent())) {
            MToast.showToast(this, "请选择会员类型");
            return;
        }
        if (TextUtils.isEmpty(mBinding.itemContacts.getContent().trim())) {
            Toast.makeText(this, "请填写联系人", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(mBinding.itemContactsPhone.getContent().trim())) {
            Toast.makeText(this, "请填写联系电话", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!CheckUtils.isMobile(mBinding.itemContactsPhone.getContent().trim())) {
            Toast.makeText(this, "请填写正确的联系电话", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(mBinding.cfkNotes.getEditContent().trim())) {
            Toast.makeText(this, "请输入邀请说明", Toast.LENGTH_SHORT).show();
            return;
        }
        mJoinEntity.setCooperationBusiness(mBinding.cfkBusiness.getEditContent());    // 合作业务[v1.0.9]
        mJoinEntity.setCooperationExpected(mBinding.itemCooperationExpected.getContent());    // 合作预期[v1.0.9]
        mJoinEntity.setMembershipRequirements(mBinding.itemMemberRequirements.getContent());// 会费要求[v1.0.9]
        mJoinEntity.setInviteContent(mBinding.cfkNotes.getEditContent().trim()); // 申请描述 后期作废
        mJoinEntity.setInvitationInstructions(mBinding.cfkNotes.getEditContent().trim()); // 申请描述
        mJoinEntity.setApplyBusiness(mBinding.cfkBusiness.getEditContent().trim()); // 合作业务
        mJoinEntity.setUserName(mBinding.itemContacts.getContent());
        mJoinEntity.setUserPhone(mBinding.itemContactsPhone.getContent()); //用户联系名
        List<AppendFieldsView.AppendField> data = mBinding.fieldsLayout.getData(); //用户联系名
        List<ParamDtosEntity> paramDtos = new ArrayList<>();
        if (data != null && data.size() > 0) {
            for (AppendFieldsView.AppendField datum : data) {
                if (!TextUtils.isEmpty(datum.title) && !TextUtils.isEmpty(datum.content)) {
                    paramDtos.add(new ParamDtosEntity(datum.title, datum.content));
                }
            }
        }
        mJoinEntity.setParamDtos(paramDtos);
        Map<String, List<CommonPopEntity>> typeMap = null;
        if (isFlag) {
            if (memberTypes != null && memberTypes.size() > 0) {
                typeMap = CopyUtils.memberTypeToJson(memberTypes);
            }
        } else {
            typeMap = CopyUtils.memberTypeToJson(memberTypes);
        }
        if (typeMap != null) {
            mJoinEntity.setFirstCategory(getCategoryNos(typeMap.get("firstCategory")));
            mJoinEntity.setSecondCategory(getCategoryNos(typeMap.get("secondCategory")));
            mJoinEntity.setThirdCategory(getCategoryNos(typeMap.get("thirdCategory")));
            mJoinEntity.setFourCategory(getCategoryNos(typeMap.get("fourCategory")));
            mJoinEntity.setFiveCategory(getCategoryNos(typeMap.get("fiveCategory")));
        }
        sModel.memberJoin(mJoinEntity);
    }

    private List<String> getCategoryNos(List<CommonPopEntity> list) {
        List<String> strings = new ArrayList<>();
        if (list == null || list.size() == 0) {
            return strings;
        }
        for (CommonPopEntity popEntity : list) {
            strings.add(popEntity.getNo());
        }
        return strings;
    }

    private List<String> getArrays(List<String> list) {
        if (list == null || list.size() == 0) {
            return new ArrayList<>();
        }
        return list;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_OK && requestCode == MemberConfig.REQ_MEMBER_TYPE) {
            memberTypes = (List<CommonPopEntity>) intent.getSerializableExtra("MEMBER_DATA");
            if (memberTypes != null && memberTypes.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (CommonPopEntity memberType : memberTypes) {
                    sb.append(memberType.getTypeName()).append("、");
                }
                String str = sb.substring(0, sb.toString().length() - 1);
                mBinding.itemType.setContent(str);
            } else {
                mBinding.itemType.setContent("");
            }
        }
    }

    public void showEmptyView() {

    }

}
